package com.zzyl.chinamobileai.controller;


import com.zzyl.chinamobileai.service.IChatHistoryService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.function.Consumer;

/**
 * 聊天controller
 */
@RestController
@RequestMapping("/ai")
public class ChatController {
    @Autowired
    private ChatClient chatClient;
    @Autowired
    private IChatHistoryService chatHistoryService;


    /**
     * 流式调用-普通字符串
     * flux是异步非阻塞的模型
     * @param prompt
     * @return
     */
    @PostMapping(value = "/chat",produces = "text/html;charset=UTF-8")
    public Flux<String> stream(String prompt,String chatId){
        chatHistoryService.saveChatHistory("chat",chatId);
        return chatClient.prompt(prompt)
                //把我们自己生成chatId传给ChatMemory
                .advisors(new Consumer<ChatClient.AdvisorSpec>() {
                    @Override
                    public void accept(ChatClient.AdvisorSpec advisorSpec) {
                        advisorSpec.param(ChatMemory.CONVERSATION_ID,chatId);
                    }
                })
                .stream().content();
    }

}
